package com.cyzy.config;

import com.alibaba.fastjson.JSON;
import com.cyzy.pojo.ChatMessage;
import com.cyzy.pojo.Netizen;
import com.cyzy.service.MessageService;
import com.cyzy.utils.MessageUtils;
import com.cyzy.utils.SpringContextUtils;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cuncun
 * @create 2025-05-29 下午7:30
 */

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)
@Component
public class ChatEndpoint {

    private static final Map<String,Session> onlineUsers = new ConcurrentHashMap<>();

    //建立websocket连接后，被调用
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) throws IOException {
        System.out.println("WebSocket 连接建立");

        System.out.println(config.getUserProperties()+ " ------config");
        // 获取用户信息
        String userId = (String) config.getUserProperties().get("userId");
        String username = (String) config.getUserProperties().get("username");
        //获取历史记录ID
        String conversationId = (String) config.getUserProperties().get("conversationId");
        //获取用户类型
        String senderType = (String) config.getUserProperties().get("senderType");
        System.out.println(conversationId + "-----conversationId");

        System.out.println(userId + " ----- " + username);
        if (userId == null || username == null) {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "认证失败"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        //读取聊天记录
        MessageService messageService = SpringContextUtils.getBean(MessageService.class);

        List<ChatMessage> chatMessages = messageService.chatHistory(conversationId);

        for (ChatMessage chatMessage : chatMessages) {
            System.out.println(chatMessage + " ----chatMessage");
            String json = JSON.toJSONString(chatMessage);
            session.getBasicRemote().sendText(json);

        }
        System.out.println("用户登录成功: " + userId + " - " + username);

        String userIdd = senderType + userId;
        System.out.println(userIdd + "发送方id");
        // 把 session 存入 map，用于后续消息推送
        onlineUsers.put(userIdd, session);
    }


//    浏览器发送消息到服务端，该方法被调用
    @OnMessage
    public void onMessage(Session session,String message){

        ChatMessage chatMessage = new ChatMessage();
        try {
            Netizen msg = JSON.parseObject(message, Netizen.class);
            System.out.println(session.getUserProperties() + " -------56");
            System.out.println(msg + "-----msg");
            String toUserId = msg.getToUserId();// 接收方ID
            chatMessage.setReceiverId(Long.valueOf(toUserId));
            String content = msg.getContent();     // 消息内容
            chatMessage.setContent(content);
            chatMessage.setType("text");
            // 获取发送方 userId（来自握手阶段）
            String senderId = (String) session.getUserProperties().get("userId");
            chatMessage.setSenderId(Long.valueOf(senderId));
            System.out.println(senderId + "________senderId");
            // 获取发送方类型（来自握手阶段）
            String senderType = (String) session.getUserProperties().get("senderType");
            chatMessage.setSenderType(senderType);
            System.out.println(senderType + " ----senderTypedddd");

            //获取聊天会话id
            String conversationId = (String) session.getUserProperties().get("conversationId");
            System.out.println(conversationId + " ----conversationIddddd");
            chatMessage.setConversationId(conversationId);
            //将发送的消息存储到数据库中
            MessageService messageService = SpringContextUtils.getBean(MessageService.class);
            System.out.println(chatMessage + " ------存储");
            messageService.saveChatHistory(chatMessage);
            // 构造消息
            String json = JSON.toJSONString(chatMessage);
            // 发送给目标用户
            String userId = null;
            if(senderType.equals("driver")){
                userId = "passenger" + toUserId;
            }else{
                userId = "driver" + toUserId;
            }

            System.out.println(userId + " ---toUserId");
            Session receiverSession = onlineUsers.get(userId);
            if (receiverSession != null && receiverSession.isOpen()) {
                receiverSession.getBasicRemote().sendText(json);
            } else {
                System.out.println("目标用户不在线: " + toUserId);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //断开websocket连接时被调用
    @OnClose
    public void OnClose(Session session){
        String userId = (String) session.getUserProperties().get("userId");
        if (userId != null) {
            onlineUsers.remove(userId);
            System.out.println("用户下线: " + userId);
        }
    }

    // 出现错误时调用
    @OnError
    public void onError(Throwable throwable) {
        System.err.println("WebSocket 出现错误: " + throwable.getMessage());
        throwable.printStackTrace();
    }
}
